#include "processbar.h"
#include<string.h>
#include<unistd.h>
#include<time.h>
#include<stdlib.h>
#define SIZE 101
typedef void (*callback_t)(double,double);
//double total = 2048.0;
double speed = 10;

double Speed()
{
  srand(time(NULL));
  int ret = rand()%10;    
  return ret;
}

//更新进度
void FlushProcess(double total,double curr)
{
  if(total<curr)
    curr = total;
  double rate = curr/total*100;//计算比例
  int cnt = (int)rate;//通过比例来看给buff填充多少个*
  char processbuff[SIZE];//buff提前控制容量
  memset(processbuff,'\0',sizeof(processbuff));
  int i = 0;
  for(;i < cnt ;i++)
  {
    processbuff[i] = '*';//提前填充
  }

  //后打印 刷新
  static char proc[] = {'|','/','-','\\'};
  static int len = sizeof(proc);
  static int index = 0;
  printf("[%-100s][%.2lf%%][%c]\r",processbuff,rate,proc[index++]);
  index %= len;
  fflush(stdout);
}

//下载
void Download(int total,callback_t cb)
{
  double curr = 0;//下载量
  while(curr <= total)
  {
    cb(total,curr);//更新进度
    curr += Speed();
    if(curr > total)
    {
      cb(total,curr);//确保更新到100%
    }
    usleep(30000);
  }
  printf("\n");
}


//version1
////边填充边打印
//void Process()
//{
//  char processbuff[SIZE];
//  memset(processbuff,'\0',sizeof(processbuff));
//  int cnt = 0;
//  char proc[] = {'|','/','-','\\'};
//  while(cnt <= 100)
//  {
//   int n = cnt % sizeof(proc);
//    printf("[%-100s][%d%%][%c]\r",processbuff,cnt,proc[n]);
//    fflush(stdout);
//    processbuff[cnt++]='*';
//    usleep(50000);
//  }
//  printf("\n");
//}
